package com.smartEdu.service;

import java.lang.reflect.Method;
//import java.util.Iterator;
import java.util.List;
import java.util.Map;
//import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationObjectSupport;

import com.smartEdu.Annotation.AbsAnnotation;
import com.smartEdu.commons.ClassStatic;
import com.smartEdu.commons.LogCvt;
import com.smartEdu.commons.Tag_Tips;
import com.smartEdu.commons.system.AcademicCommon;
import com.smartEdu.commons.system.AppContext;
import com.smartEdu.dao.InitDao;
import com.smartEdu.handler.redis.RedisImpl;
import com.smartEdu.model.NewsSimpleModel;
import com.smartEdu.model.UserModel;
import com.smartEdu.module.thrift.common.ThriftServerIface;
import com.smartEdu.module.thrift.server.helloworld.HelloWorldServer;
import com.smartEdu.utils.JsonUtil;

import redis.clients.jedis.Jedis;

public class StartComplete extends WebApplicationObjectSupport implements ApplicationListener<ContextRefreshedEvent>{

	@Autowired
	@Qualifier("initDao")
	private InitDao initDao;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private HelloWorldServer helloWorldServer;
	
	@Autowired
	private AppContext appContext;
	
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		if (Tag_Tips.APPLICATIONINITFLAG) {
			return;
		}
		// 根容器为Spring容器  
        if(event.getApplicationContext().getParent()==null){
        	appContext.setContext(event.getApplicationContext());
        	ClassStatic.appContext = event.getApplicationContext();
            Map<String,Object> beans = event.getApplicationContext().getBeansWithAnnotation(com.smartEdu.Annotation.AbsAnnotation.class);  
            for(Object bean:beans.values()){  
                System.err.println(bean==null?"null":bean.getClass().getName());  
            }  
            System.err.println("=====ContextRefreshedEvent====="+event.getSource().getClass().getName());  
        }
		try {
			registerHook();
    		initRedis();
    		initToken();
    		initNotice();
    		initNews();
    		initUser();
    		AcademicCommon.GetInstance().SetRedis(initDao.initAcademic());
    		helloWorldServer.init();
    		Tag_Tips.APPLICATIONINITFLAG=true;
		} catch (Exception e) {
			LogCvt.error("redis初始化失败",e);
			System.exit(0);
		}
	}
	
	public void registerHook() {
		Map<String, Object> map = appContext.getContext().getBeansWithAnnotation(ThriftServerIface.class);
		Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                try {
                	map.forEach((key,value)->{
							try {
								Method method = value.getClass().getMethod("stop");
								method.invoke(value);
								LogCvt.info(key+"->TServer注销成功");
							} catch (Exception e) {
								LogCvt.error(key+"->TServer注销失败",e);
							}
                	});
                    LogCvt.error("JVM关闭钩子执行成功");
                } catch (Exception e) {
                    LogCvt.error("JVM关闭钩子执行失败",e);
                }
            }
        });
	}

    public void initRedis(){
		if (ClassStatic.redis==null) {
//    		WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
			WebApplicationContext wac=getWebApplicationContext();
    		ClassStatic.redis=(RedisImpl)wac.getBean("redis");
		}
		LogCvt.info("redis初始化完毕");
	}
    
    public void initNews(){
    	List<NewsSimpleModel> models=null;
    	Jedis jedis=null;
    	try {
    		models=initDao.initNews();
    		jedis=ClassStatic.redis.getResource();
    		if (jedis.exists(Tag_Tips.NEWS)) {
    			jedis.del(Tag_Tips.NEWS);
			}
    		String value=null;
    		for(int i=0;i<models.size();i++){;
    			value=JsonUtil.toJson(models.get(i));
    			jedis.hset(Tag_Tips.NEWS,models.get(i).getPk(),value);
    		}
		}
    	catch (Exception e) {
			LogCvt.error("初始化News失败",e);
		}
    	finally {
    		models=null;
    		ClassStatic.redis.returnResource(jedis);
		}
    }
    
    public void initNotice(){
    	List<NewsSimpleModel> models=null;
    	Jedis jedis=null;
    	try {
    		models=initDao.initNotice();
    		jedis=ClassStatic.redis.getResource();
    		if (jedis.exists(Tag_Tips.NOTICE)) {
    			jedis.del(Tag_Tips.NOTICE);
			}
    		String value=null;
    		for(int i=0;i<models.size();i++){;
    			value=JsonUtil.toJson(models.get(i));
    			jedis.hset(Tag_Tips.NOTICE,models.get(i).getPk(),value);
    		}
		}
    	catch (Exception e) {
			LogCvt.error("初始化Notice失败",e);
		}
    	finally {
    		models=null;
    		ClassStatic.redis.returnResource(jedis);
		}
    }
    
    public void initUser(){
    	List<UserModel> models=null;
    	Jedis jedis=null;
    	try {
    		models=userService.getAllUser();
    		jedis=ClassStatic.redis.getResource();
    		if (jedis.exists(Tag_Tips.USER)) {
    			jedis.del(Tag_Tips.USER);
			}
    		for(int i=0;i<models.size();i++){
    			jedis.hset(Tag_Tips.U+models.get(i).getId(),Tag_Tips.NAME,models.get(i).getName());
    		}
    		models.clear();
    		models=userService.getAllUserTeacher();
    		for(int i=0;i<models.size();i++){;
    			jedis.hset(Tag_Tips.U+models.get(i).getId(),Tag_Tips.NAME,models.get(i).getName());
    		}
		}
    	catch (Exception e) {
			LogCvt.error("初始化User失败",e);
		}
    	finally {
    		models=null;
    		ClassStatic.redis.returnResource(jedis);
		}
    }
    
    public void initToken(){
    	List<Map<String, Object>> models=null;
    	Jedis jedis=null;
    	try {
    		models=initDao.initToken();
    		jedis=ClassStatic.redis.getResource();
    		jedis.flushAll();
    		if (jedis.exists(Tag_Tips.TOKENMAP)) {
    			jedis.del(Tag_Tips.TOKENMAP);
			}
//    		Iterator it=null;
//    		Entry entry=null;
    		for(int i=0;i<models.size();i++){
//    			it = models.get(i).entrySet().iterator();
//    			while(it.hasNext()){
//    				entry = (Entry)it.next();
//    				jedis.hset(Tag_Tips.TOKENMAP,entry.getKey().toString(),entry.getValue().toString());
//    			}
    			jedis.hset(Tag_Tips.TOKENMAP, models.get(i).get("token").toString(), models.get(i).get("leasttime").toString());
    		}
		}
    	catch (Exception e) {
			LogCvt.error("初始化Token失败",e);
		}
    	finally {
    		models=null;
    		ClassStatic.redis.returnResource(jedis);
		}
    }
    /**
     * 初始化学期信息
     */
    public void InitAcademic() {
    	
    }
}
